package com.atguigu.gmall.realtime.function;

import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.JdbcUtil;
import com.atguigu.gmall.realtime.util.RedisUtil;
import com.atguigu.gmall.realtime.util.ThreadPoolUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/30 13:53
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> {
    
    private ThreadPoolExecutor threadPool;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        threadPool = ThreadPoolUtil.getThreadPool();
    }
    
    @Override
    public void asyncInvoke(T input,
                            ResultFuture<T> resultFuture) throws Exception {
        // 在线程中去使用客户端读取维度数据
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                Connection phoenixConnection = null;
                Jedis redisClient = null;
                try {
                    phoenixConnection = JdbcUtil.getPhoenixConnection(Constant.PHOENIX_URL);
                    
                    redisClient = RedisUtil.getRedisClient();
                    addDim(phoenixConnection, redisClient, input, resultFuture);
                    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (phoenixConnection != null) {
                        try {
                            phoenixConnection.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    if (redisClient != null) {
                        redisClient.close();
                    }
                }
            }
        });
    }
    
    protected abstract void addDim(Connection phoenixConnection,
                                   Jedis redisClient,
                                   T input,
                                   ResultFuture<T> resultFuture);
}